package com.tech.cloudapp.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

public class Util {
    public static String nextString(int len) {
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        String keyString = "abcdefghijklmnopqrstuvwxyz0123456789";
        for(int i = 0; i < len; ++i) {
            stringBuilder.append(keyString.charAt(random.nextInt(keyString.length())));
        }
        return stringBuilder.toString();
    }




    public static Map jsonToMap(String jsonStr)
    {
        JSONObject json = JSON.parseObject(jsonStr);
        return (Map)json;
    }

    public static void parseFileTypeResp(String decryString, HttpServletResponse response) throws Exception {
        JSONObject respJson = JSON.parseObject(decryString);
        JSONObject head = respJson.getJSONObject("Head");
        JSONObject data = respJson.getJSONObject("Data");
        String code = head.getString("Txn_Rsp_Cd_Dsc");
        if(code.equals("0000000000") && data.containsKey("data") ) {
            String filename = Util.nextString(16);
            if(data.containsKey("fileName"))
            {
                filename = data.getString("fileName");
            }

            if(data.getString("data") == null ||  data.getString("data").equals(""))
            {
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(decryString);
                return;
            }

            byte[] zipData = data.getBytes("data");
            byte[] filedata = GzipUtils.unzip(zipData);
            if(filedata == null)
            {
                System.out.println("response is null");
                return;
            }

            InputStream inputStreamResp = new ByteArrayInputStream(filedata);
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] rspByte = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStreamResp.read(rspByte)) > 0) {
                outputStream.write(rspByte, 0, len);
            }
            inputStreamResp.close();
        }else
        {
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(decryString);
        }

    }



    public static void parseFileTypeSaveload(String decryString) throws Exception {
        JSONObject respJson = JSON.parseObject(decryString);
        JSONObject head = respJson.getJSONObject("Head");
        JSONObject data = respJson.getJSONObject("Data");
        String code = head.getString("Txn_Rsp_Cd_Dsc");
        if(code.equals("0000000000") && data.containsKey("data") ) {
            String filename = Util.nextString(16);
            if(data.containsKey("fileName"))
            {
                filename = data.getString("fileName");
            }

            if(data.getString("data") == null ||  data.getString("data").equals(""))
            {

                return;
            }

            //byte[] zipData = data.getBytes("data");
           // byte[] filedata = GzipUtils.unzip(zipData);
            byte[] filedata = data.getBytes("data");
            if(filedata == null)
            {
                System.out.println("response is null");
                return;
            }


            File file = new File("D:\\"+filename);
            if(!file.exists())
            {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(filedata,0,filedata.length);
            fos.close();
        }else
        {

        }

    }



    /**
     * 获取现在时间
     * @return返回字符串格式yyyyMMddHHmmss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(currentTime);
        System.out.println("TIME:::"+dateString);
        return dateString;
    }
    /**
     * 由年月日时分秒+3位随机数
     * 生成流水号
     * @return
     */
    public static String Getnum(String prefix){
        String t = getStringDate();
        String serial = prefix + "_" +t ;
        return serial;
    }


    /**
     * 数字格式化
     * @param num 数字
     * @param formatStr 格式 #.#
     * @return
     */
    public static Double DoubleFormat(Double num,String formatStr)
    {
        DecimalFormat decimalFormat = new DecimalFormat(formatStr);
        String result = decimalFormat.format(num);
        double roundedNum = Double.parseDouble(result);
        return  roundedNum;
    }


}
